<template>
  <div class="ai-pet-view">
    <h2 class="pet-page-title">宠物形象</h2>
    <div class="my-pet-section">
      <!-- 优先使用接口 avatar -->
      <div :style="{ backgroundImage: `url(${currentAvatar})` }" class="my-pet-img"></div>
    </div>
    <div class="collapse-header">
      <div class="pet-upload-title">宠物信息</div>
      <van-icon :name="true ? 'arrow-down' : 'arrow-up'" class="collapse-arrow" />
    </div>
    <van-cell-group>
      <!-- 可折叠的更改形象区域 -->
      <div class="collapse-section">
        <div class="collapse-header" @click="toggleCollapse">
          <div class="pet-upload-title">更改宠物形象</div>
          <van-icon :name="isCollapsed ? 'arrow-down' : 'arrow-up'" class="collapse-arrow" />
        </div>

        <div v-show="!isCollapsed" class="collapse-content">
          <div class="pet-upload-section">
            <div class="pet-upload-title">上传宠物照片</div>
            <van-uploader v-model="petData.photo" />
          </div>

          <van-field v-model="petData.description" label="文字描述" type="textarea" placeholder="请输入文字描述"
            class="description-field" />

          <div class="preset-pets-grid-2">
            <div v-for="(img, index) in generatedPets" :key="index" class="pet-result-2" @click="selectPet(index)">
              <img :src="img" alt="生成的宠物" :class="{ 'pet-selected': selectedPet === index }" />
            </div>
          </div>

          <div class="btn-wrapper">
            <van-button @click="handleGenerate" class="generate-btn">
              {{ hasGenerated ? '重新生成' : '生成形象' }}
            </van-button>
          </div>

          <!-- 预设宠物形象区域 -->
          <div class="collapse-section">
            <div class="collapse-header" @click="presetCollapsed = !presetCollapsed">
              <div class="pet-upload-title">预设宠物形象</div>
              <van-icon :name="presetCollapsed ? 'arrow-down' : 'arrow-up'" class="collapse-arrow" />
            </div>
            <div v-show="!presetCollapsed" class="collapse-content">
              <div class="preset-pets-grid">
                <div v-for="(img, index) in presetPets" :key="index" class="pet-result" style="margin-top:8px"
                  @click="selectedPreset = index">
                  <img :src="img" :class="{ 'pet-selected': selectedPreset === index }" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="selectedPet !== null" class="confirm-btn-wrapper" v-show="!isCollapsed">
        <van-button @click="confirmPet" class="confirm-btn">确认选择</van-button>
      </div>
    </van-cell-group>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import type { UploaderFileListItem } from 'vant'
import { useRouter } from 'vue-router'
import { usePetStore } from '@/stores/pet'     // ← 确保用的是你纯前端版的 store
import { storeToRefs } from 'pinia'

const router = useRouter()
const petStore = usePetStore()
const { pet } = storeToRefs(petStore)

/** 展示优先级：avatar -> normal_gif -> hidden_gif */
const currentAvatar = computed(() => {
  return pet.value.avatar;
})

/** 折叠与生成 */
const isCollapsed = ref(true)
const hasGenerated = ref(false)
const presetCollapsed = ref(true)

const petData = ref({
  description: '',
  photo: [] as UploaderFileListItem[],
})

/** 随机生成的候选 */
const generatedPets = ref<string[]>([])
const selectedPet = ref<number | null>(null)

/** 预设候选 */
const presetPets = ref([
  '/assets/pet/preset1.png',
  '/assets/pet/preset2.png',
  '/assets/pet/preset3.png',
  '/assets/pet/preset4.png',
  '/assets/pet/preset5.png',
  '/assets/pet/preset6.png',
  '/assets/pet/preset7.png',
  '/assets/pet/preset8.png'
])
const selectedPreset = ref<number | null>(null)

/** 生成两张随机图片（示例用占位符） */
function generateRandomPets(count: number) {
  const imgs: string[] = []
  for (let i = 0; i < count; i++) {
    if (i === 0) {
      imgs.push('https://ku-sheet-server.baidu-int.com/uploader/f/zoGlknZigMrR1wXq.png?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzcxMTQsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNjUxNCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.zkBZkxAKMzLFlhfP0Ak5Sdclg6ooo1etMsNiHlnrS4M');
    } else if (i === 1) {
      imgs.push('https://ku-sheet-server.baidu-int.com/uploader/f/SmThtKdDDwr42NB1.jpg?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2Mzc0MzgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNjgzOCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.10cQI_5_cOlwWrXaXziAoopLMbN6dIGjUKP3tzI-hmA');
    } else
      imgs.push(`https://via.placeholder.com/150?text=Pet+${Math.random().toString(36).slice(2, 7)}`)
  }
  return imgs
}

const handleGenerate = () => {
  const newPets = generateRandomPets(2)
  generatedPets.value = [...newPets, ...generatedPets.value].slice(0, 6)
  hasGenerated.value = true
  // 选择状态互斥：清空预设选择
  selectedPreset.value = null
}

const selectPet = (index: number) => {
  selectedPet.value = index
  // 选择状态互斥：清空预设选择
  selectedPreset.value = null
}

/** 选择预设（与 selectPet 互斥） */
const selectPreset = (index: number) => {
  selectedPreset.value = index
  selectedPet.value = null
}

/** 确认后：直接写入 Pinia（并持久化到 localStorage，如果 store 里实现了） */
const confirmPet = () => {
  let selectedUrl: string | null = null
  if (selectedPet.value !== null) {
    selectedUrl = generatedPets.value[selectedPet.value]
  } else if (selectedPreset.value !== null) {
    selectedUrl = presetPets.value[selectedPreset.value]
  }
  if (!selectedUrl) return

  // 👇 用 store 的方法更新（约定使用 patch）
  petStore.patch({
    avatar: selectedUrl,
  })

  toggleCollapse()
}

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}
</script>


<style scoped>
.ai-pet-view {
  background: #fff;
  border-radius: 8px;
  max-width: 800px;
  margin: auto;
}

.pet-page-title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  color: #8C5C2A;
  margin-bottom: 16px;
}

.my-pet-section {
  display: flex;
  margin: 10px 0;
  justify-content: center;
}

.my-pet-img {
  width: 180px;
  height: 180px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  object-fit: cover;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
}

.pet-upload-section {
  margin: 16px 0 8px 16px;
}

.pet-upload-title {
  font-size: 15px;
  color: var(--van-field-label-color);
  margin-bottom: 8px;
}

.btn-wrapper {
  margin: 10px 16px 0 16px;
  padding-bottom: 16px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.generate-btn {
  border-radius: 8px;
}

.generated-pets {
  margin-top: 24px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  justify-items: center;
  gap: 10px;
  padding-bottom: 24px;
}

.pet-result {
  text-align: center;
  width: 65px;
  height: 65px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pet-result-2 {
  text-align: center;
  width: 130px;
  height: 130px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pet-result-2 img {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.pet-result img {
  width: 75px;
  height: 75px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.pet-selected {
  border: 4px solid #FFD59E;
  box-shadow: 0 0 0 6px #FFF3E0;
}

.confirm-btn-wrapper {
  display: flex;
  justify-content: flex-end;
  margin: 16px 16px 0 16px;
  padding-bottom: 16px;
}

.confirm-btn {
  border-radius: 8px;
}

.preset-pets-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 6px;
  padding: 8px;
  justify-items: center;
}

.preset-pets-grid-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 6px;
  padding: 8px;
  justify-items: center;
}

/* 折叠区域样式 */
.collapse-section {
  border-top: 1px solid #ebedf0;
  margin-top: -1px;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  cursor: pointer;
}

.collapse-arrow {
  transition: transform 0.3s;
  color: #969799;
  font-size: 16px;
}

.collapse-content {
  border-radius: 0 0 8px 8px;
}

.description-field :deep(.van-field__control) {
  min-height: 60px !important;
  max-height: 100px !important;
}
</style>
